import { scheduleCallback } from "../scheduler/scheduler";
import { beginWork } from "./beginWork";
import { commitWork } from "./commitWork";

// work in progress 正在进行的工作
let wip: any = null;

// 保存 Fiber 根节点
let wipRoot: any = null;

export function scheduleUpdateOnFiber(fiber: any) {
  wip = fiber;
  wipRoot = fiber;

  // window.requestIdleCallback(workLoop);
  scheduleCallback(workLoop);
}

// function workLoop(deadline: any) {
//   // 有要进行的工作并且有空闲时间时执行
//   while (wip && deadline.timeRemaining() > 0) {
//     performUnitOfWork();
//   }
//   // 处理完后提交fiber链表
//   commitRoot();
// }

function workLoop(timer: any) {
  while (wip) {
    if (timer < 0) {
      // 只有该任务还没到期时才回进入该if
      return false;
    }
    performUnitOfWork();
  }

  // 处理完后提交fiber链表
  commitRoot();
  return true;
}

function performUnitOfWork() {
  beginWork(wip);

  // 1. 处理子节点
  const child = wip.child;
  if (wip.child) {
    wip = child;
    return;
  }

  // 没有子节点则运行completeWork
  completeWork();

  // 2. 处理兄弟节点
  let next = wip;
  while (next) {
    if (next.sibling) {
      wip = next.sibling;
      return;
    }

    // 走到这证明当前节点既没有子节点也没有兄弟节点
    completeWork();

    // 尝试从父节点找兄弟节点
    next = next.return;
  }

  // 走到这证明fiber树已经处理完毕
  wip = null;
}

function commitRoot() {
  commitWork(wipRoot);
  wipRoot = null;
}

function completeWork() {}
